from selenium import webdriver
import time
import csv
import re
def search_product(key):
    driver.find_element_by_id('key').send_keys(key)
    driver.find_element_by_class_name('button').click()
    driver.maximize_window()
    time.sleep(5)
def get_product():
    try:
        driver.implicitly_wait(5)
        time.sleep(5)
        goods = driver.find_elements_by_class_name('gl-item')  # 定位到每一个商品
        # print(goods)
        for good in goods:
            detail_url = good.find_element_by_tag_name('a').get_attribute('href')  # class="p-name p-name-type-2"
            p_name = good.find_element_by_css_selector('.p-name  em').text.replace('\n', '')  # . 用class命名用'.' ID 用'#'
            price = driver.find_element_by_css_selector('.p-price i').text  # i为下级标签
            p_comment = driver.find_element_by_css_selector('.p-commit a').text
            print(p_name, detail_url, price, p_comment)
            msg = '''
            商品:%s
            链接:%s
            价格:%s
            评论:%s
            ''' % (p_name, detail_url, price, p_comment)
            print(msg)
        print('长度',len(p_name))
        for good in goods:
            detail_url = good.find_element_by_xpath('.//div[@class="p-img"]/a/@href')
            print(detail_url)
    except Exception as e:
        print(e)
def main():
    search_product(keyword)
    get_product()
if __name__=='__main__':
    keyword=input('请输入你要搜索的商品关键字:')
    driver=webdriver.Chrome()
    driver.get('https://www.jd.com/')
    main()
